<template>
  <div>

    <Spin size="large" fix v-if="loading"></Spin>

    <section class="section">
      <resource-category :sort="{type: 1, name: '图片'}" :active="sortActive" @on-change="onSortChange" @on-sorts="uploadSorts"></resource-category>
    </section>
    <section class="section">
      <div class="material-search-add">
        <div class="material-search">
          <Input search enter-button placeholder="标题" v-model="keyword" @on-search="getImages" />
        </div>
        <div class="material-add">
          <Button type="primary" @click="addImages">添加图片</Button>
        </div>
      </div>
    </section>
    <section class="section">
      <div class="material-list">
        <ui-material-item :item="item" v-for="item in items" :key="item.key" @on-del="delImage" @on-edit="onEditImage" />
      </div>
    </section>

    <div class="acea-row row-right page">
      <Page :total="total" :current="page" :page-size="limit" show-total @on-change="pageChange" />
    </div>

    <Modal v-model="showModal" title="添加图片" width="750px" footer-hide :mask-closable="false">
      <ui-uploader :upload-header="uploadHeader" multiple :sorts="sorts" @on-success="handleSuccess" @on-add-imgurl="handleAddImage" />
    </Modal>
    <Spin size="large" fix v-if="spinShow"></Spin>

    <Modal v-model="editImageModal" title="修改图片信息" width="750px" :mask-closable="false" @on-ok="handleEditImage">
      <Form :model="editFormData" label-position="top">
        <FormItem label="图片名称">
          <Input v-model.trim="editFormData.title" maxlength="30" show-word-limit></Input>
        </FormItem>
        <FormItem label="图片URL">
          <Input v-model.trim="editFormData.img_url" maxlength="255" show-word-limit></Input>
        </FormItem>
        <FormItem label="图片描述">
          <Input v-model.trim="editFormData.img_des" maxlength="200" show-word-limit type="textarea" :rows="2"></Input>
        </FormItem>
        <FormItem label="图片宽度">
          <InputNumber :max="99999" :min="0" v-model="editFormData.img_width" class="w-100"></InputNumber>
        </FormItem>
        <FormItem label="图片高度">
          <InputNumber :max="99999" :min="0" v-model="editFormData.img_height" class="w-100"></InputNumber>
        </FormItem>
        <FormItem label="排序">
          <InputNumber :max="99999" :min="0" v-model="editFormData.img_order" class="w-100"></InputNumber>
        </FormItem>
      </Form>
    </Modal>

  </div>
</template>

<script>
import { getList, store, update, destroy } from '@/api/resource/picture'
import util from '@/libs/util'
import ResourceCategory from './components/Category'
import UiMaterialItem from '@/components/ui/UiMaterialItem.vue'
import UiUploader from '@/components/ui/UiUploader.vue'
export default {
  name: 'PictureList',
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getImages()
    })
  },
  components: {
    ResourceCategory,
    UiMaterialItem,
    UiUploader
  },
  data () {
    return {
      showModal: false,
      spinShow: false,
      cid: 0,
      uploadHeader: {},
      sorts: [],
      items: [],
      sortActive: 0,
      keyword: '',
      page: 1,
      limit: 20,
      total: 0,
      loading: false,
      // 修改图片
      editImageModal: false,
      editFormId: 0,
      editFormData: {
        title: '',
        img_url: '',
        img_des: '',
        img_width: '',
        img_height: '',
        img_order: 0,
      }
    }
  },
  computed: {},
  mounted () {
    this.uploadHeader['Authori-zation'] = 'Bearer ' + util.cookies.get('token')
    this.getImages()
  },
  methods: {
    uploadSorts (sorts) {
      this.sorts = sorts
    },

    // 显示资源列表
    getImages () {
      this.loading = true
      getList({ cid: this.cid, page: this.page, limit: this.limit, keyword: this.keyword }).then(async res => {
        if (res.status === 200) {
          this.total = res.data.count
          this.items = res.data.list.map(item => {
            return {
              ...item,
              key: `${item.id}`,
              checked: false
            }
          })
        } else {
          this.$Notice.error({ title: res.msg })
        }
        this.loading = false
      }).catch(res => {
        this.loading = false
        this.$Notice.error({ title: res.msg })
      })
    },

    onSortChange (id) {
      this.cid = id
      this.page = 1
      this.getImages()
    },
    handleSuccess ({ res, file, cid }) {
      if (res.status !== 200) {
        if (file.size > (2 * 1024 * 1024)) {
          this.$Message.warning({
            content: '图片大小超过2M，请修改后重试',
            duration: 3
          });
          return
        } else {
          this.$Message.warning({
            content: JSON.stringify(res.msg),
            duration: 6
          });
          return
        }
      }
      this.showModal = false
      this.spinShow = true
      const { data } = res
      const { name } = file
      store({
        cid,
        title: name,
        img_url: data.img_url,
        img_width: data.img_width,
        img_height: data.img_height,
      }).then(() => {
        this.spinShow = false
        this.sortActive = cid
        this.cid = id

        this.getImages()
      })
    },
    // 添加图片
    handleAddImage (row) {
      this.spinShow = true
      store(row).then(async res => {
        if (res.status === 200) {
          this.showModal = false
          this.spinShow = false
          this.sortActive = row.cid
          this.cid = res.id

          this.getImages()
        } else {
          this.$Notice.error({ title: res.msg })
        }
        this.spinShow = false
      }).catch(res => {
        this.spinShow = false
        this.$Notice.error({ title: res.msg })
      })
    },

    addImages () {
      this.showModal = true
    },
    delImage (id) {
      this.$Modal.confirm({
        title: '删除图片',
        content: '确定要删除这张图片吗?',
        onOk: () => {
          destroy(id).then(() => {
            this.$Notice.success({ title: '删除成功' })
            this.getImages()
          })
        },
        onCancel: () => { }
      })
    },

    // 编辑图片信息
    onEditImage (row) {
      this.editFormId = row.id
      this.editFormData = {
        title: row.title,
        img_url: row.img_url,
        img_des: row.img_des,
        img_width: row.img_width,
        img_height: row.img_height,
        img_order: row.img_order,
      }
      this.editImageModal = true
    },
    // 编辑图片信息
    handleEditImage () {
      this.loading = true
      update(this.editFormId, this.editFormData).then(async res => {
        if (res.status === 200) {
          this.$Notice.success({ title: '修改成功' })
          this.getImages()
        } else {
          this.$Notice.error({ title: res.msg })
          this.loading = false
        }
      }).catch(res => {
        this.loading = false
        this.$Notice.error({ title: res.msg })
      })
    },

    pageChange (index) {
      this.page = index
      this.getImages()
    },
  }
}
</script>

<style lang="scss">
.w-100 {
  width: 100%;
}
</style>
